function swap(arr, i, j) {
  [arr[i], arr[j]] = [arr[j], arr[i]];
}

function swap() {
  
}

function bubbleSort(arr) {
  for (let i = 0; i < arr.length; i++) {
    let isSwap = false;
    for (let j = 0; j < arr.length - i - 1; j++) {
      if (arr[j] > arr[j + 1]) {
        swap(arr, j, j + 1);
        isSwap = true;
      }
    }
    if (!isSwap) break;
  }
}

function selectSort(arr) {
  for (let i = 0; i < arr.length; i++) {
    let minIndex = i;
    for (let j = i + 1; j < arr.length; j++) {
      if (arr[j] < arr[minIndex]) minIndex = j;
    }
    swap(arr, i, minIndex);
  }
}

function insertSort(arr) {
  for (let i = 1; i < arr.length; i++) {
    for (let j = i - 1; j >= 0 && arr[j] > arr[j + 1]; j--) {
      swap(arr, j, j + 1);
    }
  }
}

function merge(arr, l, mid, r) {
  let help = [];
  let i = 0;
  let p1 = l;
  let p2 = mid + 1;
  while (p1 <= mid && p2 <= r) {
    help[i++] = arr[p1] > arr[p2] ? arr[p2++] : arr[p1++];
  }

  while (p1 <= mid) {
    help[i++] = arr[p1++];
  }

  while (p2 <= r) {
    help[i++] = arr[p2++];
  }

  for (let j = 0; j < help.length; j++) {
    // 可用 System.arraycopy 代替
    arr[l + j] = help[j];
  }
}

function mergeSortLR(arr, l, r) {
  if (l < r) {
    let mid = Math.floor(l + (r - l) / 2);
    mergeSortLR(arr, l, mid);
    mergeSortLR(arr, mid + 1, r);
    merge(arr, l, mid, r);
  }
}

function mergeSort(arr) {
  mergeSortLR(arr, 0, arr.length - 1);
}

const arr = [5, 2, 1, 4, 6];
mergeSort(arr);
console.log(arr);
